package com.xyc.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xyc.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;

@Controller
public class HelloServlet {
    @RequestMapping(value = {"/index","/hello"})
    public ModelAndView index(){
        ModelAndView modelAndView =  new ModelAndView("index");
        modelAndView.getModel().put("test","传递参数内容");
        return modelAndView;
    }

    @RequestMapping(value = "/test")
    public String test(User user,Model model){
        System.out.println(user);
        if(true) throw new RuntimeException();
        model.addAttribute("test","简写测试");
        return "test";
    }

    @RequestMapping("/get")
    public String param(@RequestParam(value = "username",required = false) String name){//使用@RequestParam接收参数
        System.out.println(name);
        return "redirect:/hello";
    }

    @ResponseBody
    @RequestMapping(value = "/json", produces = "application/json")
    public String json(){
        JSONArray array = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name","罗星");
        jsonObject.put("age",18);

        array.add(jsonObject);
        return array.toString();
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam MultipartFile file) throws IOException {
        File fileObj = new File("test.png");
        file.transferTo(fileObj);
        System.out.println("用户上传的文件已保存到："+fileObj.getAbsolutePath());
        return "文件上传成功！";
    }
}
